package org.crl.blogsystem.controller;


import cn.dev33.satoken.stp.StpUtil;
import org.crl.blogsystem.entity.Like;
import org.crl.blogsystem.message.ResponseMessage;
import org.crl.blogsystem.repository.LikeRepository;
import org.crl.blogsystem.service.IBlogService;
import org.crl.blogsystem.service.ILikeService;
import org.crl.blogsystem.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/blog/like")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true", methods = {RequestMethod.GET, RequestMethod.POST,  RequestMethod.PUT, RequestMethod.DELETE})
public class LikeController {
    @Autowired
    ILikeService likeService;

    @PutMapping("/{blog_id}")
    public ResponseMessage<String> like(@PathVariable("blog_id") Long blogId) {
        StpUtil.checkLogin();
        Long userId = StpUtil.getLoginIdAsLong();
        if (likeService.existsByUser_IdAndBlog_Id(userId, blogId)) {
            likeService.deleteByUserIdAndBlogId(userId, blogId);
            return ResponseMessage.success("取消点赞");
        } else {
            likeService.like(blogId, userId);
            return ResponseMessage.success("点赞成功");
        }
    }

    @GetMapping("/{blog_id}")
    public ResponseMessage<Boolean> isLiked(@PathVariable("blog_id") Long blogId) {
        StpUtil.checkLogin();
        Long userId = StpUtil.getLoginIdAsLong();
        boolean isLiked = likeService.existsByUser_IdAndBlog_Id(userId, blogId);
        return ResponseMessage.success(isLiked);
    }
}
